# JSON价目表提取器 - 为拼多多商家版优化版
# 需要安装 ImportExcel 模块: Install-Module ImportExcel -Force

Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

# 检查并安装 ImportExcel 模块
function Install-RequiredModules {
    if (!(Get-Module -ListAvailable -Name ImportExcel)) {
        $result = [System.Windows.Forms.MessageBox]::Show(
            "需要安装 ImportExcel 模块才能导出 Excel 文件。是否现在安装？", 
            "模块检查", 
            [System.Windows.Forms.MessageBoxButtons]::YesNo, 
            [System.Windows.Forms.MessageBoxIcon]::Question
        )
        
        if ($result -eq [System.Windows.Forms.DialogResult]::Yes) {
            try {
                Install-Module ImportExcel -Force -Scope CurrentUser
                [System.Windows.Forms.MessageBox]::Show("ImportExcel 模块安装成功！", "安装完成", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Information)
                return $true
            }
            catch {
                [System.Windows.Forms.MessageBox]::Show("模块安装失败: $($_.Exception.Message)", "安装错误", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error)
                return $false
            }
        }
        else {
            return $false
        }
    }
    return $true
}

# 从 URL 下载 JSON 数据
function Get-JsonFromUrl {
    param([string]$Url)
    
    try {
        $webClient = New-Object System.Net.WebClient
        $webClient.Encoding = [System.Text.Encoding]::UTF8
        $jsonContent = $webClient.DownloadString($Url)
        return $jsonContent
    }
    catch {
        throw "无法从 URL 下载数据: $($_.Exception.Message)"
    }
}

# 提取价目表数据并导出到 Excel - 优化版 for 拼多多
function Export-PriceListToExcel {
    param(
        [string]$JsonContent,
        [string]$OutputPath
    )
    
    try {
        # 解析 JSON 数据
        $jsonData = $JsonContent | ConvertFrom-Json
        
        # 检查价目表数据是否存在
        if (-not $jsonData.priceList -or -not $jsonData.priceList.tables) {
            throw "JSON 文件中未找到价目表数据 (priceList.tables)"
        }
        
        # 创建 Excel 数据数组
        $excelData = @()
        
        foreach ($table in $jsonData.priceList.tables) {
            foreach ($row in $table.rows) {
                $dataRow = @{}
                $size = ""  # 用于拼“尺寸”
                $material = ""  # 用于存“材料”
                
                # 遍历表头和对应的值
                for ($i = 0; $i -lt $table.headers.Count; $i++) {
                    $header = $table.headers[$i]
                    $value = if ($i -lt $row.Count) { $row[$i] } else { "" }
                    
                    # 把“规格”、“内径”、“扣长”、“外高”拼成“尺寸”
                    switch ($header) {
                        "规格" { if ($value) { $size += "规格 $value " } }
                        "内径" { if ($value) { $size += "内径 $value " } }
                        "扣长" { if ($value) { $size += "扣长 $value " } }
                        "外高" { if ($value) { $size += "外高 $value " } }
                        "材质" { $material = $value }
                    }
                }
                
                # 去掉多余空格，确保“尺寸”通俗易懂
                $dataRow["尺寸"] = $size.Trim()
                $dataRow["材料"] = $material
                
                # 添加到 Excel 数据中
                $excelData += [PSCustomObject]$dataRow
            }
        }
        
        # 导出到 Excel，只保留“尺寸”和“材料”两列
        $excelData | Export-Excel -Path $OutputPath -AutoSize -WorksheetName "拼多多价目表" -Show
        
        return $true
    }
    catch {
        throw "导出 Excel 时发生错误: $($_.Exception.Message)"
    }
}

# 创建主窗体
$form = New-Object System.Windows.Forms.Form
$form.Text = "JSON价目表提取器 - 拼多多版"
$form.Size = New-Object System.Drawing.Size(650, 550)
$form.StartPosition = "CenterScreen"
$form.FormBorderStyle = "FixedDialog"
$form.MaximizeBox = $false
$form.MinimizeBox = $true

# 标题标签
$titleLabel = New-Object System.Windows.Forms.Label
$titleLabel.Text = "JSON价目表提取工具 - 为拼多多商家版优化"
$titleLabel.Font = New-Object System.Drawing.Font("Microsoft YaHei", 14, [System.Drawing.FontStyle]::Bold)
$titleLabel.Size = New-Object System.Drawing.Size(580, 35)
$titleLabel.Location = New-Object System.Drawing.Point(35, 15)
$titleLabel.TextAlign = "MiddleCenter"
$titleLabel.ForeColor = "DarkBlue"
$form.Controls.Add($titleLabel)

# 文件选择组
$fileGroupBox = New-Object System.Windows.Forms.GroupBox
$fileGroupBox.Text = "选择JSON文件"
$fileGroupBox.Font = New-Object System.Drawing.Font("Microsoft YaHei", 9)
$fileGroupBox.Size = New-Object System.Drawing.Size(580, 80)
$fileGroupBox.Location = New-Object System.Drawing.Point(35, 60)
$form.Controls.Add($fileGroupBox)

# 文件路径文本框
$filePathTextBox = New-Object System.Windows.Forms.TextBox
$filePathTextBox.Size = New-Object System.Drawing.Size(420, 25)
$filePathTextBox.Location = New-Object System.Drawing.Point(15, 25)
$filePathTextBox.ReadOnly = $true
$filePathTextBox.BackColor = "White"
$fileGroupBox.Controls.Add($filePathTextBox)

# 浏览文件按钮
$browseButton = New-Object System.Windows.Forms.Button
$browseButton.Text = "浏览文件"
$browseButton.Size = New-Object System.Drawing.Size(120, 30)
$browseButton.Location = New-Object System.Drawing.Point(445, 23)
$browseButton.BackColor = "LightSteelBlue"
$fileGroupBox.Controls.Add($browseButton)

# URL 输入组
$urlGroupBox = New-Object System.Windows.Forms.GroupBox
$urlGroupBox.Text = "或输入JSON文件URL"
$urlGroupBox.Font = New-Object System.Drawing.Font("Microsoft YaHei", 9)
$urlGroupBox.Size = New-Object System.Drawing.Size(580, 80)
$urlGroupBox.Location = New-Object System.Drawing.Point(35, 150)
$form.Controls.Add($urlGroupBox)

# URL 文本框
$urlTextBox = New-Object System.Windows.Forms.TextBox
$urlTextBox.Size = New-Object System.Drawing.Size(540, 25)
$urlTextBox.Location = New-Object System.Drawing.Point(15, 25)
$urlTextBox.Add_Enter({
    if ($this.Text -eq "请输入JSON文件的URL地址...") {
        $this.Text = ""
        $this.ForeColor = "Black"
    }
})
$urlTextBox.Add_Leave({
    if ($this.Text -eq "") {
        $this.Text = "请输入JSON文件的URL地址..."
        $this.ForeColor = "Gray"
    }
})
$urlTextBox.Text = "请输入JSON文件的URL地址..."
$urlTextBox.ForeColor = "Gray"
$urlGroupBox.Controls.Add($urlTextBox)

# 输出设置组
$outputGroupBox = New-Object System.Windows.Forms.GroupBox
$outputGroupBox.Text = "输出设置"
$outputGroupBox.Font = New-Object System.Drawing.Font("Microsoft YaHei", 9)
$outputGroupBox.Size = New-Object System.Drawing.Size(580, 80)
$outputGroupBox.Location = New-Object System.Drawing.Point(35, 240)
$form.Controls.Add($outputGroupBox)

# 输出路径文本框
$outputPathTextBox = New-Object System.Windows.Forms.TextBox
$outputPathTextBox.Size = New-Object System.Drawing.Size(420, 25)
$outputPathTextBox.Location = New-Object System.Drawing.Point(15, 25)
$outputPathTextBox.Text = [System.IO.Path]::Combine([Environment]::GetFolderPath("Desktop"), "拼多多价目表.xlsx")
$outputGroupBox.Controls.Add($outputPathTextBox)

# 选择输出路径按钮
$outputBrowseButton = New-Object System.Windows.Forms.Button
$outputBrowseButton.Text = "选择路径"
$outputBrowseButton.Size = New-Object System.Drawing.Size(120, 30)
$outputBrowseButton.Location = New-Object System.Drawing.Point(445, 23)
$outputBrowseButton.BackColor = "LightSteelBlue"
$outputGroupBox.Controls.Add($outputBrowseButton)

# 操作按钮区域
$buttonPanel = New-Object System.Windows.Forms.Panel
$buttonPanel.Size = New-Object System.Drawing.Size(580, 50)
$buttonPanel.Location = New-Object System.Drawing.Point(35, 330)
$form.Controls.Add($buttonPanel)

# 导出按钮
$exportButton = New-Object System.Windows.Forms.Button
$exportButton.Text = "导出Excel"
$exportButton.Font = New-Object System.Drawing.Font("Microsoft YaHei", 10, [System.Drawing.FontStyle]::Bold)
$exportButton.Size = New-Object System.Drawing.Size(120, 40)
$exportButton.Location = New-Object System.Drawing.Point(460, 5)
$exportButton.BackColor = "LightGreen"
$buttonPanel.Controls.Add($exportButton)

# 清空按钮
$clearButton = New-Object System.Windows.Forms.Button
$clearButton.Text = "清空"
$clearButton.Size = New-Object System.Drawing.Size(80, 40)
$clearButton.Location = New-Object System.Drawing.Point(370, 5)
$clearButton.BackColor = "LightCoral"
$buttonPanel.Controls.Add($clearButton)

# 进度条
$progressBar = New-Object System.Windows.Forms.ProgressBar
$progressBar.Size = New-Object System.Drawing.Size(580, 25)
$progressBar.Location = New-Object System.Drawing.Point(35, 390)
$progressBar.Style = "Continuous"
$form.Controls.Add($progressBar)

# 状态标签
$statusLabel = New-Object System.Windows.Forms.Label
$statusLabel.Text = "就绪"
$statusLabel.Size = New-Object System.Drawing.Size(580, 25)
$statusLabel.Location = New-Object System.Drawing.Point(35, 420)
$statusLabel.ForeColor = "Blue"
$statusLabel.Font = New-Object System.Drawing.Font("Microsoft YaHei", 9)
$form.Controls.Add($statusLabel)

# 浏览文件事件
$browseButton.Add_Click({
    $openFileDialog = New-Object System.Windows.Forms.OpenFileDialog
    $openFileDialog.Filter = "JSON文件 (*.json)|*.json|所有文件 (*.*)|*.*"
    $openFileDialog.Title = "选择JSON文件"
    
    if ($openFileDialog.ShowDialog() -eq "OK") {
        $filePathTextBox.Text = $openFileDialog.FileName
        
        # 清空 URL 输入
        if ($urlTextBox.Text -ne "请输入JSON文件的URL地址...") {
            $urlTextBox.Text = ""
        }
        
        $statusLabel.Text = "已选择文件: " + [System.IO.Path]::GetFileName($openFileDialog.FileName)
        $statusLabel.ForeColor = "Green"
    }
})

# 选择输出路径事件
$outputBrowseButton.Add_Click({
    $saveFileDialog = New-Object System.Windows.Forms.SaveFileDialog
    $saveFileDialog.Filter = "Excel文件 (*.xlsx)|*.xlsx"
    $saveFileDialog.Title = "选择输出文件"
    $saveFileDialog.FileName = "拼多多价目表.xlsx"
    
    if ($saveFileDialog.ShowDialog() -eq "OK") {
        $outputPathTextBox.Text = $saveFileDialog.FileName
    }
})

# 清空按钮事件
$clearButton.Add_Click({
    $filePathTextBox.Text = ""
    $urlTextBox.Text = "请输入JSON文件的URL地址..."
    $urlTextBox.ForeColor = "Gray"
    $statusLabel.Text = "已清空输入"
    $statusLabel.ForeColor = "Blue"
    $progressBar.Value = 0
})

# 导出 Excel 事件
$exportButton.Add_Click({
    try {
        # 检查模块
        $statusLabel.Text = "检查必需模块..."
        $statusLabel.ForeColor = "Blue"
        $progressBar.Value = 10
        [System.Windows.Forms.Application]::DoEvents()
        
        if (!(Install-RequiredModules)) {
            $statusLabel.Text = "模块检查失败"
            $statusLabel.ForeColor = "Red"
            $progressBar.Value = 0
            return
        }
        
        # 获取 JSON 内容
        $statusLabel.Text = "读取JSON数据..."
        $progressBar.Value = 30
        [System.Windows.Forms.Application]::DoEvents()
        
        $jsonContent = ""
        
        if ($filePathTextBox.Text -and (Test-Path $filePathTextBox.Text)) {
            # 从文件读取
            $jsonContent = Get-Content -Path $filePathTextBox.Text -Raw -Encoding UTF8
        }
        elseif ($urlTextBox.Text.Trim() -and $urlTextBox.Text -ne "请输入JSON文件的URL地址...") {
            # 从 URL 下载
            $statusLabel.Text = "从URL下载数据..."
            $progressBar.Value = 40
            [System.Windows.Forms.Application]::DoEvents()
            $jsonContent = Get-JsonFromUrl -Url $urlTextBox.Text.Trim()
        }
        else {
            throw "请选择JSON文件或输入URL地址"
        }
        
        if (-not $jsonContent) {
            throw "无法读取JSON数据"
        }
        
        # 导出 Excel
        $statusLabel.Text = "解析数据并导出Excel文件..."
        $progressBar.Value = 70
        [System.Windows.Forms.Application]::DoEvents()
        
        $success = Export-PriceListToExcel -JsonContent $jsonContent -OutputPath $outputPathTextBox.Text
        
        if ($success) {
            $progressBar.Value = 100
            $statusLabel.Text = "导出完成！文件已保存到: " + [System.IO.Path]::GetFileName($outputPathTextBox.Text)
            $statusLabel.ForeColor = "Green"
            
            [System.Windows.Forms.MessageBox]::Show(
                "价目表已成功导出到：`n$($outputPathTextBox.Text)`n`n只包含两列：尺寸（规格 内径 扣长 外高）和材料", 
                "导出成功", 
                [System.Windows.Forms.MessageBoxButtons]::OK, 
                [System.Windows.Forms.MessageBoxIcon]::Information
            )
        }
    }
    catch {
        $progressBar.Value = 0
        $statusLabel.Text = "导出失败: $($_.Exception.Message)"
        $statusLabel.ForeColor = "Red"
        
        [System.Windows.Forms.MessageBox]::Show(
            "导出失败：`n$($_.Exception.Message)", 
            "错误", 
            [System.Windows.Forms.MessageBoxButtons]::OK, 
            [System.Windows.Forms.MessageBoxIcon]::Error
        )
    }
})

# URL 输入框变化事件
$urlTextBox.Add_TextChanged({
    if ($this.Text.Trim() -and $this.Text -ne "请输入JSON文件的URL地址...") {
        $filePathTextBox.Text = ""  # 清空文件选择
    }
})

# 文件路径变化事件
$filePathTextBox.Add_TextChanged({
    if ($this.Text.Trim()) {
        # 清空 URL 输入
        if ($urlTextBox.Text -ne "请输入JSON文件的URL地址...") {
            $urlTextBox.Text = "请输入JSON文件的URL地址..."
            $urlTextBox.ForeColor = "Gray"
        }
    }
})

# 显示窗体
$form.ShowDialog() | Out-Null